package io.renren.modules.wiki.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageInfo;
import io.renren.modules.wiki.dto.CategoryEntityDto;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.wiki.dao.CategoryDao;
import io.renren.modules.wiki.entity.CategoryEntity;
import io.renren.modules.wiki.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }



    public PageInfo<CategoryEntityDto>  findTree(int page, int pageSize,int parentId) {
        var parentPage= this.findByParentIdWithPage(page,pageSize,parentId);
        var parentListCopy=new ArrayList<CategoryEntityDto>();
        for (CategoryEntityDto categoryEntity : parentPage.getList()) {
            var nodeId = categoryEntity.getId();
            var childrenList= categoryDao.findByParentId(nodeId);
            categoryEntity.setChildren(childrenList);
            parentListCopy.add(categoryEntity);
        }
        parentPage.setList(parentListCopy);
        return parentPage;
    }

    @Override
    public CategoryEntity getById(Integer id) {
        return categoryDao.findById(id);
    }

    public PageInfo<CategoryEntityDto> findByParentIdWithPage(int page, int pageSize, int parentId) {
        com.github.pagehelper.PageHelper.startPage(page, pageSize);
        return new com.github.pagehelper.PageInfo<>(categoryDao.findByParentId(parentId));
    }
}